package com.sunstar.cwcamerademo

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import com.sunstar_j.strict_databinding.DataBindingConfig
import com.sunstar_j.strict_databinding.SBindActivity
import com.sunstar_j.strict_databinding.XMLBindingData
import kotlinx.coroutines.*
import kotlin.math.log

class TesterPage : SBindActivity(), CoroutineScope by MainScope() {

    private val testViewModel = TestViewModel.instance
    var handler: Handler? = null

    override fun initBindingConfig(): DataBindingConfig {
        checkColdBoot()
        return DataBindingConfig(
            R.layout.activity_tester_page,
            XMLBindingData(BR.testVM, testViewModel),
            XMLBindingData(
                BR.hotRebootClick,
                View.OnClickListener {
                    launch {
                        withContext(Dispatchers.IO) { testViewModel.startHotReboot() }
                        handler = Handler(mainLooper)
                        startActivity(Intent(this@TesterPage, MainActivity::class.java))
                    }
                },
            ),
            XMLBindingData(BR.coldRebootClick, View.OnClickListener {
                launch {
                    startColdBoot()
                }
            })
        )
    }

    private fun checkColdBoot() {
        Log.e("TesterPage", "checkColdBoot: ${testViewModel.type},${testViewModel.isTester.value}", )
        if (testViewModel.type == TesterType.COLD_REBOOT && testViewModel.isTester.value == true) {
            launch {
                withContext(Dispatchers.IO) {
                    delay(3000)
                }
                startColdBoot()
            }
        }
        testViewModel.isTester.value = false
    }

    suspend fun startColdBoot() {
        withContext(Dispatchers.IO) { testViewModel.startColdReboot() }
        startActivity(Intent(this@TesterPage, MainActivity::class.java))
    }

    override fun onResume() {
        super.onResume()
        launch {
            val isTester = withContext(Dispatchers.IO) {
                testViewModel.checkHotTesterComplete()
            }
            if (testViewModel.type == TesterType.HOT_REBOOT && isTester && testViewModel.isTester.value == true) { //如果是热启动且未完成 两秒后继续测试
                handler?.postDelayed({
                    startActivity(Intent(this@TesterPage, MainActivity::class.java))
                }, 2000)
            }
        }

    }

}